package com.example.exam10.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.exam10.AppDatabase;
import com.example.exam10.R;
import com.example.exam10.adapter.PersonAdapter;
import com.example.exam10.dao.PersonDao;
import com.example.exam10.entity.Person;

import java.util.List;

public class exam10 extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "exam10.class";
    Button btnSearch, btnInsert;
    EditText etSearch;
    List<Person> personList;
    PersonDao personDao;
    PersonAdapter adapter;
    RecyclerView recyclerView;

    private void init() {
        personDao = AppDatabase.getInstance(this).getPersonDao();
        personList = personDao.loadAllPersons();
        for (Person p : personList) {
            Log.d(TAG, "initinkk: " + p.getId());
            Log.d(TAG, "initinkk: " + p.getName());
            Log.d(TAG, "initinkk: " + p.getPhone());
        }
        recyclerView = findViewById(R.id.recycler_view);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        adapter = new PersonAdapter(personList);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exam10);
        init();
        btnInsert = findViewById(R.id.btn_insert);
        btnSearch = findViewById(R.id.btn_search);
        etSearch = findViewById(R.id.et_search);
        btnInsert.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_insert:
                Intent intent = new Intent(exam10.this, PersonActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_search:
                personList = personDao.searchPerson(etSearch.getText().toString());
                adapter.setPersonList(personList);
                recyclerView.setAdapter(adapter);
                break;
            default:
                break;
        }
    }

}